package com.traveldream.entity_managers;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.ejb.EJBContext;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.codec.digest.DigestUtils;

import com.traveldream.entities.Group;
import com.traveldream.entities.User;

/**
 * Session Bean implementation class UserManagerBean
 */
@Stateless
public class CustomerManagerBean implements CustomerManager {

	// bisogna indicare che si usa la persistenza configurata nel package Common
	@PersistenceContext(unitName="TravelDreamCommon")
	EntityManager em;

	@Resource
	private EJBContext context;
	
	@Override
	public User create(User c) {
		if(em.createNamedQuery("User.findByEmail", User.class).setParameter("email", c.getEmail()).getResultList().size()==0)
		{
			List<Group> groups = new ArrayList<Group>();
			groups.add(Group.CUSTOMER);
			c.setGroups(groups);
			
			c.setPassword(DigestUtils.sha256Hex(c.getPassword()));
			// persist & flush em
			em.persist(c);
			em.flush();
			em.refresh(c);
			// return persisted object
			return c;
		}
		return null;
	}
	
	@Override
	public User getAuthenticatedUser(){
		return em.find(User.class,context.getCallerPrincipal().getName());
	}

	@Override
	public List<User> findAll() {
		Query query = em.createNamedQuery("User.findAll",User.class);
		List<User> results=new ArrayList<User>();
   		for( Object o : query.getResultList() ) 
   		results.add((User)o);
		return results;
	}
	
}
